nonlocal
- pozwalające na odwoływanie się do już istniejących zmiennych, nie globalnych. Przeszukiwany jest scope, który jest najbliższym zamykającym dla istniejącego__closure__
In [ ]:
def make_counter():
i = 0
def counter():
print(i)
return counter
ct1 = make_counter()
ct2 = make_counter()
ct1()
ct1()
ct2()
ct2()
In [ ]:
def make_counter():
i = 0
def counter():
print(i)
i += 1
return counter
ct1 = make_counter()
ct2 = make_counter()
ct1(), ct1(), ct2(), ct2()
In [ ]:
def make_counter():
i = 0
def counter():
nonlocal i
print(i)
i += 1
return counter
ct1 = make_counter()
ct2 = make_counter()
ct1()
ct1()
ct2()
ct2()
In [ ]:
def make_counter():
i = 0
b = 0
def counter():
nonlocal i, b
print(i, b)
i += 1
b -= 1
return counter
ct1 = make_counter()
print(", ".join(dir(ct1)))
print(ct1.__closure__)
ct1()
ct1()
ct1.__closure__ = (-5, 5)
In [ ]:
def make_counter(i):
class context():
x = i
def counter():
print(context.x)
context.x += 1
return counter
ct1, ct2 = make_counter(10), make_counter(-10)
ct1(), ct1()
ct2(), ct2()